package com.worldtvs.online.view;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.bzydroid.network.http.AbsRequestHandler;
import com.bzydroid.network.http.NetworkResponse;
import com.bzydroid.network.http.client.BzydroidHttpClient;
import com.bzydroid.network.http.exception.BzydroidNetworkExeception;
import com.bzydroid.network.http.response.HttpJSONObjectResponse;
import com.bzydroid.utils.BzydroidLog;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.worldtv.lives.R;
import com.worldtvs.online.E4KidsConfig;
import com.worldtvs.online.E4KidsSlidingMenuActivity;
import com.worldtvs.online.adapter.AlbumIndexFragmentAdapter;
import com.worldtvs.online.adapter.AlbumIndexFragmentAdapter.IClickPla;
import com.worldtvs.online.adapter.SlideShowImageAdapter;
import com.worldtvs.online.adapter.SlideShowImageAdapter.setOnClickItemListener;
import com.worldtvs.online.adapter.VideoIndexFragmentAdapter;
import com.worldtvs.online.adapter.VideoIndexFragmentAdapter.ClickItemVideo;
import com.worldtvs.online.customize.CustomGridView;
import com.worldtvs.online.customize.NotInterceptInPager;
import com.worldtvs.online.database.DBAdapter;
import com.worldtvs.online.database.DBFunction;
import com.worldtvs.online.database.MySQLiteHelper;
import com.worldtvs.online.entity.InfoAds;
import com.worldtvs.online.entity.InfoAlbum;
import com.worldtvs.online.entity.InfoTotalAlbum;
import com.worldtvs.online.entity.InfoVideo;
import com.worldtvs.online.service.RequestService;
import com.worldtvs.online.util.Debug;
import com.worldtvs.online.util.PreferenceHelper;
import com.worldtvs.online.util.Util;

public class IndexNoTabActivity extends E4KidsSlidingMenuActivity implements
		OnClickListener {
	PreferenceHelper mpPreferenceHelper;
	private ImageView ivABCancelSearch;
	private ImageView ivABSearch;
	private EditText edtABSearch;
	private LinearLayout llContainEdt;
	private ImageView tvABTitle;
	private ImageView ivABLogo;

	private VideoIndexFragmentAdapter adapterVideo;
	private AlbumIndexFragmentAdapter adapterAlbum;
	private SlideShowImageAdapter adapterAds;

	private ArrayList<InfoAds> dataAds;
	private ArrayList<InfoVideo> dataVideo;
	private ArrayList<InfoAlbum> dataPlaylist;
	private ArrayList<InfoAlbum> datalist;
	public ArrayList<InfoTotalAlbum> dataTotalAlbums;

	private NotInterceptInPager viewPager;
	private CustomGridView gvVideo;
	private RelativeLayout rlContainPager;

	private TextView tvTitleVideo;

	private LinearLayout llLoading;

	private ScrollView scroller;

	private View root;

	private Handler slideHandler;

	private boolean isTouch = false;
	private int pageViewPager;
	private LinearLayout llListCat;
	private static AdView adView;
	private InterstitialAd interstitial;
	RelativeLayout rlContainAds;
	DBFunction dbf;
	View vListCat;
	TextView tvTitle;
	CustomGridView gvListCat;
	LayoutInflater mInflater;
	MySQLiteHelper mHelper;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_v2_index);

		this.setBehindContentView(R.layout.frame_layout_container);
		// this.getSlidingMenu().setSecondaryMenu(R.layout.frame_right_container);
		this.setDefaultBar();
		configLeftSlideMenu();
		// this.removeSlidingMenu();
		mHelper = new MySQLiteHelper(this);
		dbf = new DBFunction(DBAdapter.getObj(this));
		dbf.getVideo();
		dbf.getSlide();
		dbf.getAlbum();
		dbf.getTotalAlbum();
mpPreferenceHelper=new PreferenceHelper(this);
		init();

	}

	private void init() {
		mInflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		rlContainAds = (RelativeLayout) findViewById(R.id.rlContainAds);
		interstitial = new InterstitialAd(getBaseContext());
		interstitial.setAdUnitId("ca-app-pub-4674514998412720/7904097694");
		adView = (AdView) this.findViewById(R.id.ad);

		AdRequest adRequest = new AdRequest.Builder()
				.addTestDevice(AdRequest.DEVICE_ID_EMULATOR).addTestDevice("")
				.build();
		
		adView.loadAd(adRequest);
		interstitial.loadAd(adRequest);
		interstitial.setAdListener(new AdListener() {
			@Override
			public void onAdLoaded() {
				displayInterstitial();
			}
		});
		ivABCancelSearch = actionBar.getIvABCancelSearch();
		ivABSearch = actionBar.getIvABSearch();
		edtABSearch = actionBar.getEdtABSearch();
		llContainEdt = actionBar.getLlContainEdt();
		ivABLogo = actionBar.getIvABLogo();
		tvABTitle = actionBar.getIvTitle();

		ivABLogo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
//				toggle();
			}
		});

		// edtABSearch.setOnEditorActionListener(searchAction);
		ivABSearch.setOnClickListener(this);
		ivABCancelSearch.setOnClickListener(this);

		edtABSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
		edtABSearch.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView arg0, int actionID,
					KeyEvent arg2) {
				// RequestUrlService.requestSearchNameSinger(delegateSinger,
				// "tuan hung");
				String text = edtABSearch.getText().toString().trim();
				if (!text.equals("") || !TextUtils.isEmpty(text)) {

					goActivitySearch(IndexNoTabActivity.this,
							SearchResultActivity.class,
							E4KidsConfig.KEY_INTENT_SEARCH, text);
				}
				return true;
			}
		});

		slideHandler = new Handler();

		viewPager = (NotInterceptInPager) findViewById(R.id.viewpager);

		DisplayMetrics metrics = getResources().getDisplayMetrics();
		int width = metrics.widthPixels;

		int widthImage = width
				- 2
				* (getResources()
						.getDimensionPixelOffset(R.dimen.item_video_padding));
		int heightImage = (width * 67) / 100;

		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				widthImage, heightImage);

		int marginPager = getResources().getDimensionPixelOffset(
				R.dimen.item_video_padding);
		params.setMargins(marginPager, 0, marginPager, 0);
		viewPager.setLayoutParams(params);

		gvVideo = (CustomGridView) findViewById(R.id.gvVideo);
		tvTitleVideo = (TextView) findViewById(R.id.tvTitleVideo);
		tvTitleVideo.setVisibility(View.GONE);
		llListCat = (LinearLayout) findViewById(R.id.llCate);

		scroller = (ScrollView) findViewById(R.id.index_layout_scroller);
		scroller.setVisibility(View.VISIBLE);
		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		rlContainPager = (RelativeLayout) findViewById(R.id.index_layout_viewpager);

		dataAds = new ArrayList<InfoAds>();
		dataPlaylist = new ArrayList<InfoAlbum>();
		datalist = new ArrayList<InfoAlbum>();
		dataVideo = new ArrayList<InfoVideo>();
		dataTotalAlbums = new ArrayList<InfoTotalAlbum>();
		// load du lieu video

		dataVideo.addAll(dbf.getVideo());
		if(dataAds.size()>0){
			llLoading.setVisibility(View.GONE);
		}
		else{
			llLoading.setVisibility(View.VISIBLE);
		}
		adapterVideo = new VideoIndexFragmentAdapter(IndexNoTabActivity.this,
				dataVideo, imageLoader, options);
		gvVideo.setAdapter(adapterVideo);

		// load du lieu slide

		dataAds.addAll(dbf.getSlide());
		adapterAds = new SlideShowImageAdapter(IndexNoTabActivity.this,
				dataAds, imageLoader, options);
		viewPager.setAdapter(adapterAds);
		long t = Util.getCurrentTime() - mpPreferenceHelper.getTimeGetContact() ;
		if (t > (1*60*60*1000)){
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					mpPreferenceHelper.setTimeGetContact(System.currentTimeMillis());
				}
			}).start();
		}
		RequestService.rqHomeIndex(packageName, new RequestHome());
		// load du lieu album
		int count = dbf.getTotalAlbum().size();
		dataTotalAlbums.addAll(dbf.getTotalAlbum());
		for (int i = 0; i < count; i++) {
			dataPlaylist = new ArrayList<InfoAlbum>();
			InfoTotalAlbum mAlbum = dataTotalAlbums.get(i);
			String cat_id = mAlbum.getId();
			vListCat = mInflater.inflate(R.layout.layout_item_cat_index, null);
			tvTitle = (TextView) vListCat.findViewById(R.id.tvTitlePla);
			gvListCat = (CustomGridView) vListCat.findViewById(R.id.gvAlbum);
			datalist = new ArrayList<InfoAlbum>();
			dataPlaylist.addAll(mHelper.getAllAlbum(cat_id));
			for (int j = 0; j < dataPlaylist.size(); j++) {
				InfoAlbum objAlbum = dataPlaylist.get(j);
				InfoAlbum infoAlbum = parsePla(objAlbum);
				datalist.add(infoAlbum);

			}
			adapterAlbum = new AlbumIndexFragmentAdapter(
					IndexNoTabActivity.this, datalist, imageLoader, options);
			gvListCat.setAdapter(adapterAlbum);
			tvTitle.setText(mAlbum.getTitle());
			llListCat.addView(vListCat, i);
			adapterAlbum.setClickPla(new IClickPla() {

				@Override
				public void clickItemPla(String id) {
					Bundle b = new Bundle();

					b.putString(E4KidsConfig.KEY_INTENT_AID, id);
					gotoActivity(ListVideoByPlaActivity.class, b);
					app.setCatID(Integer.valueOf(id));
				}
			});

		}

		adapterVideo.setIclickItemVideo(new ClickItemVideo() {

			@Override
			public void clickItem(String vid, String id) {
				Bundle bundle = new Bundle();
				bundle.putString(E4KidsConfig.KEY_INTENT_VID, vid);
				bundle.putString(E4KidsConfig.KEY_INTENT_LINK, id);
				gotoActivity(PlayVideoYoutbe.class, bundle);
			}
		});
		adapterAds.setOnClickItemListener(new setOnClickItemListener() {

			@Override
			public void onCallClick(boolean isPla, String vid, String linkVideo) {
				Debug.debug("IsPlay : " + isPla + "\nID : " + vid);
//				if (isPla) {
//					Bundle bundle = new Bundle();
//					bundle.putString(E4KidsConfig.KEY_INTENT_AID, vid);
//					gotoActivity(ListVideoByPlaActivity.class, bundle);
//				} else {
					Bundle bundle = new Bundle();
					bundle.putString(E4KidsConfig.KEY_INTENT_VID, vid);
					bundle.putString(E4KidsConfig.KEY_INTENT_LINK, linkVideo);

					gotoActivity(PlayVideoYoutbe.class, bundle);
//				}
			}

		});
		pageViewPager = 0;
		updateUI();

		// viewPager.setOnPageChangeListener(this);

		viewPager.setOnTouchListener(onSlideTouch);

	}
	 public void displayInterstitial() {
	        if (interstitial.isLoaded()) {
	          interstitial.show();
	        }
	      }
	
	private InfoAlbum parsePla(InfoAlbum object) {
		InfoAlbum infoAlbum;
		String id = object.getAid();
		String name = object.getaName();
		String image = object.getaAvatar();
		infoAlbum = new InfoAlbum(id, name, image, "", "", "");
		return infoAlbum;
	}

	/** Event to handle slide-show when user on touch */
	private OnTouchListener onSlideTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_MOVE:
				isTouch = true;
				// Remove runnable when moving
				slideHandler.removeCallbacks(mRunnable);
				break;
			case MotionEvent.ACTION_UP:
				isTouch = false;
				// Repost thread
				slideHandler.postDelayed(mRunnable, 2000);
				break;

			}
			return false;
		}
	};

	protected InfoAlbum parseJsonPla(InfoAlbum object) {
		InfoAlbum objAlbum = null;
		String id = objAlbum.getAid();
		String name = objAlbum.getaName();
		String avata = objAlbum.getaAvatar();
		String cat_id = objAlbum.getCat_id();
		objAlbum = new InfoAlbum(id, name, avata, "", "", "");
		return objAlbum;
	}

	/** Runnable to auto sliding */
	private Runnable mRunnable = new Runnable() {
		@Override
		public void run() {
			if (!isTouch) {
				pageViewPager += 1;
				if (pageViewPager == adapterAds.getCount()) {
					pageViewPager = 0;
				}
				viewPager.setCurrentItem(pageViewPager, true);
			}
			slideHandler.postDelayed(mRunnable, 3000);
		}
	};

	private void updateUI() {
		new Handler().postDelayed(mRunnable, 3000);
	}

	private class RequestHome extends AbsRequestHandler {
		private InfoAds infoAds;

		@Override
		public void onWait(BzydroidHttpClient arg0) {
			super.onWait(arg0);
			llLoading.setVisibility(View.GONE);

			if (!Util.isConnectingToInternet(IndexNoTabActivity.this)) {
				scroller.setVisibility(View.VISIBLE);
				if (llLoading.getVisibility() == View.GONE) {
					llLoading.setVisibility(View.GONE);
				}
			} else {
				scroller.setVisibility(View.VISIBLE);
			}
		}

		@Override
		public void onStarted(BzydroidHttpClient arg0) {
			super.onStarted(arg0);
			BzydroidLog.debug("onStarted");
		}

		@Override
		public void onSuccess(BzydroidHttpClient arg0, NetworkResponse arg1) {

			HttpJSONObjectResponse jsonObjectResponse = (HttpJSONObjectResponse) arg0
					.getResponse();

			try {
				JSONObject object = jsonObjectResponse.toJSONObject();

				Debug.debug("Du lieu Response : " + object.toString());

				JSONObject jObjData = object
						.getJSONObject(E4KidsConfig.KEY_DATA);

				int code = jObjData.getInt(E4KidsConfig.KEY_CODE);

				if (code == 1) {
					// Debug.debug("Vao day : " + jObj);

					mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

					JSONArray jArrAds = jObjData
							.getJSONArray(E4KidsConfig.Home.KEY_ADS);

					JSONArray jArrVideo = jObjData
							.getJSONArray(E4KidsConfig.Home.KEY_VIDEO);

					JSONArray jArrCats = jObjData
							.getJSONArray(E4KidsConfig.Home.KEY_CAT);

					Debug.debug("jArrAds : " + jArrAds.toString());
					Debug.debug("jArrVideo : " + jArrVideo.toString());

					int lengthAds = jArrAds.length();
					int lengthVideo = jArrVideo.length();
					int lengthCat = jArrCats.length();

					if (lengthAds <= 0) {
						rlContainPager.setVisibility(View.GONE);
					} else {
						rlContainPager.setVisibility(View.VISIBLE);

						for (int i = 0; i < lengthAds; i++) {
							JSONObject objectAds = jArrAds.getJSONObject(i);

							String id = objectAds.getString("id");
							String title = objectAds.getString("title");
							String image = objectAds.getString("image");

							int type = objectAds.getInt("type");

							if (type == 0) {
								infoAds = new InfoAds(id, title, image, type,
										"");
							} else if (type == 1) {
								String idYoutube = objectAds
										.getString("id_youtube");
								infoAds = new InfoAds(id, title, image, type,
										idYoutube);
								dbf.insertDataSlide(id, idYoutube, title,
										image, type);

							}
							tvTitleVideo.setVisibility(View.VISIBLE);

						}
					}

					// Fill video
					if (lengthVideo <= 0) {
						gvVideo.setVisibility(View.GONE);
						tvTitleVideo.setVisibility(View.GONE);
					} else {
						gvVideo.setVisibility(View.VISIBLE);
						tvTitleVideo.setVisibility(View.VISIBLE);

						for (int i = 0; i < lengthVideo; i++) {
							JSONObject objectVideo = jArrVideo.getJSONObject(i);
							InfoVideo infoVideo = parseJsonVideo(objectVideo);

						}
					}

					// Fill List cat
					if (lengthCat <= 0) {
						llListCat.setVisibility(View.GONE);
					} else {
						llListCat.setVisibility(View.VISIBLE);
						for (int i = 0; i < lengthCat; i++) {
							JSONObject objectLstCat = jArrCats.getJSONObject(i);

							String catTitle = objectLstCat.getString("title");
							String catid = objectLstCat.getString("id");

							if (!objectLstCat.isNull("playlists")) {
								JSONArray jArrDetailCat = objectLstCat
										.getJSONArray("playlists");
								dataPlaylist = new ArrayList<InfoAlbum>();
								int lengthDetailCat = jArrDetailCat.length();
								dbf.insertDataTotalAlbum(catid, catTitle,
										lengthDetailCat);

								for (int j = 0; j < lengthDetailCat; j++) {
									JSONObject jObjDetaiCat = jArrDetailCat
											.getJSONObject(j);
									InfoAlbum infoAlbum = parseJsonPla(
											jObjDetaiCat,
											String.valueOf(lengthDetailCat),
											catid, catTitle);
									// dataPlaylist.add(infoAlbum);
								}
							}
						}
					}

					scroller.setVisibility(View.VISIBLE);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onError(BzydroidHttpClient arg0,
				BzydroidNetworkExeception arg1) {
			super.onError(arg0, arg1);
			BzydroidLog.debug("onError");

			if (!Util.isConnectingToInternet(IndexNoTabActivity.this)) {
				scroller.setVisibility(View.VISIBLE);
				if (llLoading.getVisibility() == View.GONE) {
					llLoading.setVisibility(View.GONE);
				}
			} else {
				scroller.setVisibility(View.VISIBLE);
			}
		}

		@Override
		public void onFinished(BzydroidHttpClient arg0) {
			super.onFinished(arg0);
			BzydroidLog.debug("onFinished");
			llLoading.setVisibility(View.GONE);
		}

	}

	@Override
	public void onBackPressed() {
		quitApp();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.iv_search:
			if (llContainEdt.getVisibility() == View.GONE) {
				llContainEdt.setVisibility(View.VISIBLE);
				ivABSearch.setVisibility(View.GONE);
				tvABTitle.setVisibility(View.GONE);
				edtABSearch.setFocusable(true);
				edtABSearch.requestFocus();
				showBoard(edtABSearch);
			}
			break;
		case R.id.iv_cancel:
			String text = edtABSearch.getText().toString().trim();
			if (!text.equals("")) {
				edtABSearch.setText("");
			} else {
				llContainEdt.setVisibility(View.GONE);
				ivABSearch.setVisibility(View.VISIBLE);
				tvABTitle.setVisibility(View.VISIBLE);
				edtABSearch.setFocusable(true);
				hiddenBoard(edtABSearch);
			}
			break;
		}
	}

	private class RequestAccess extends AbsRequestHandler {
		@Override
		public void onStarted(BzydroidHttpClient arg0) {
			super.onStarted(arg0);
			Debug.debug("onStarted");
		}

		@Override
		public void onSuccess(BzydroidHttpClient arg0, NetworkResponse arg1) {
			HttpJSONObjectResponse jsonObjectResponse = (HttpJSONObjectResponse) arg0
					.getResponse();

			Debug.debug("HttpJSONObjectResponse Access : "
					+ jsonObjectResponse.toString());

			try {
				JSONObject jObjResponse = new JSONObject(
						jsonObjectResponse.toString());

				JSONObject jObjData = jObjResponse.getJSONObject("data");

				int codeAccess = jObjData.getInt("code");

				app.setAccess(codeAccess);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onError(BzydroidHttpClient arg0,
				BzydroidNetworkExeception arg1) {
			super.onError(arg0, arg1);
			Debug.debug("onError");

			RequestService.rqHomeIndex(packageName, new RequestHome());
		}

		@Override
		public void onFinished(BzydroidHttpClient arg0) {
			super.onFinished(arg0);
			Debug.debug("onFinished");
			RequestService.rqHomeIndex(packageName, new RequestHome());
		}
	}

	// private void loadAccess(){
	// RequestService.rqAccess(new RequestAccess());
	// }
}
